<template>
	<div class="use-app-container" v-loading.fullscreen.lock="fullscreenLoading">
		<!-- 创建任务引导 -->
		<el-collapse>
			<el-collapse-item title="新手引导 - 如何创建任务？">
				<div class="guide-content">
					<p>
						<strong>任务名称：</strong>
						简短描述任务名称，例如“新药靶点筛选任务”。例如，任务名称应简洁且具有描述性。
					</p>
					<p>
						<strong>靶点名称：</strong>
						填写相关靶点的名称，确保名称唯一且清晰。例如：请确保名称没有歧义。
					</p>
					<p>
						<strong>任务介绍：</strong>
						概述任务的目标、背景以及重要细节，帮助团队成员更好理解任务。建议概述不超过200字，明确任务的核心目标。
					</p>
					<p>
						<strong>AI模型选择：</strong>
						根据分析需求选择一个合适的AI模型，比如“GraphDTA”、“WGNNDTA”等。
					</p>
					<p>
						<strong>筛选库：</strong>
						选择一个数据筛选库，确保后续分析的准确性。
					</p>
					<p>
						<strong>自定义筛选库：</strong>
						您可以创建自己的筛选库并上传包含化合物信息的文件，系统会自动保存。支持.txt文件格式。
					</p>
					<p>
						<strong>提交任务：</strong>
						点击“提交”按钮后，系统将开始处理该任务, 之后可在任务看板查看执行进度以及任务详情页查看结果。
					</p>
					<p>
						<strong>重置：</strong>
						如果填写有误，点击“重置”按钮将清空所有已填写的数据。
					</p>
				</div>
			</el-collapse-item>
		</el-collapse>

		<!-- 创建任务表单 -->
		<el-card class="form-section" shadow="hover">
			<el-divider content-position="left"><h1>新建任务</h1></el-divider>
			<el-steps :active="activeStep" align-center finish-status="success" class="task-steps">
				<el-step title="基本信息" icon="el-icon-edit"></el-step>
				<el-step title="选择模型" icon="el-icon-files"></el-step>
				<el-step title="选择筛选库" icon="el-icon-coin"></el-step>
				<el-step title="完成创建" icon="el-icon-upload2"></el-step>
			</el-steps>
			<el-form :model="form" label-width="120px" ref="taskForm" class="task-form">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="任务名称" prop="taskName" :rules="[{ required: true, message: '任务名称不能为空', trigger: 'blur' }]">
							<el-input v-model="form.taskName" placeholder="请输入任务名称，如“新药靶点筛选任务”" @input="updateStep"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="靶点名称" prop="targetName" :rules="[{ required: true, message: '靶点名称不能为空', trigger: 'blur' }]">
							<el-input v-model="form.targetName" placeholder="请输入靶点名称，如“EGFR”" @input="updateStep"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="任务介绍" prop="taskDescription" :rules="[{ required: true, message: '任务介绍不能为空', trigger: 'blur' }]">
							<el-input v-model="form.taskDescription" type="textarea" placeholder="请输入任务介绍，例如“用于EGFR靶点药物筛选的任务”" @input="updateStep"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="靶点序列" prop="targetSequence" :rules="[{ required: true, message: '靶点序列不能为空', trigger: 'blur' }]">
							<el-input v-model="form.targetSequence" type="textarea" placeholder="请输入靶点氨基酸序列" @input="updateStep"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="AI模型" prop="aiModel" :rules="[{ required: true, message: '请选择AI模型', trigger: 'change' }]">
							<el-select style="width: 100%" v-model="form.aiModel" placeholder="请选择AI模型" @change="updateStep">
								<el-option v-for="model in models" :key="model.model_id" :label="model.model_name" :value="model.model_id">
									{{ model.model_name }}: {{ model.model_description }}
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="筛选库" prop="screeningLibrary" :rules="[{ required: true, message: '请选择筛选库', trigger: 'change' }]">
							<el-select style="width: 100%" v-model="form.screeningLibrary" placeholder="请选择筛选库" @change="updateStep">
								<el-option v-for="library in libraries" :key="library.library_id" :label="library.library_name" :value="library.library_id">
									{{ library.library_name }}: {{ library.library_description }}
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<div class="form-actions">
					<el-button round icon='el-icon-paperclip' @click="fillExample(1)">Mpro靶点筛选</el-button>
					<el-button round icon='el-icon-paperclip'@click="fillExample(2)">EGFR靶点筛选</el-button>
					<el-button round icon='el-icon-paperclip'@click="fillExample(3)">PKMYT1靶点筛选</el-button>
				</div>

				<div class="form-actions">
<el-button type="primary" round icon="el-icon-upload2" @click="handleSubmit">提交</el-button>
<el-button type="warning" round icon="el-icon-refresh" @click="handleReset">重置</el-button>
<el-button type="info" round icon="el-icon-folder-opened" @click="openCustomLibraryPanel">自定义筛选库</el-button>

				</div>
			</el-form>
		</el-card>

		<!-- 自定义筛选库对话框 -->
		<el-dialog title="自定义筛选库" :visible.sync="customLibraryVisible" width="40%">
			<el-form :model="customLibraryForm" label-width="80px" ref="customLibraryFormRef">
				<el-form-item label="库名称" prop="libraryName" :rules="[{ required: true, message: '库名称不能为空', trigger: 'blur' }]">
					<el-input v-model="customLibraryForm.libraryName" placeholder="请输入库名称"></el-input>
				</el-form-item>
				<el-form-item label="库描述" prop="libraryDescription" :rules="[{ required: true, message: '库描述不能为空', trigger: 'blur' }]">
					<el-input v-model="customLibraryForm.libraryDescription" type="textarea" placeholder="请输入库描述"></el-input>
				</el-form-item>
				<el-form-item label="上传文件" prop="compoundFile">
					<el-upload action="#" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="1">
						<el-button plain>
							上传
							<i class="el-icon-upload el-icon--right"></i>
						</el-button>
					</el-upload>
					<div class="upload-hint">仅支持.txt格式。在上传的文本文件中，每个化合物的SMILES表示法（简明分子输入线性表示法）应该单独写在一行上，而不是将多个SMILES放在同一行。这种格式便于程序或系统正确读取和处理每个化合物的信息。</div>
				</el-form-item>
			</el-form>
			<div slot="footer">
				<el-button round @click="customLibraryVisible = false">取 消</el-button>
				<el-button type="primary"  round @click="handleCustomLibrarySubmit">提 交</el-button>
			</div>
		</el-dialog>

		<!-- 最近任务列表 -->
		<el-card class="recent-tasks-section" shadow="hover">
			<el-divider content-position="left"><h1>最近任务</h1></el-divider>
	<el-table v-if="tasks.length > 0" :data="paginatedTasks" style="width: 100%" height="400" >
				<el-table-column prop="name" label="任务名称" align="center"></el-table-column>
				<el-table-column prop="task_description" label="任务详情" align="left" width='500'></el-table-column>
				<el-table-column prop="target_name" label="靶点名称" align="center"></el-table-column>
				<el-table-column prop="status" label="状态" align="center" width='100'>
					<template v-slot="scope">
						<el-tag size="medium" effect="plain" :type="scope.row.status === 'completed' ? 'success' : scope.row.status === 'error' ? 'danger' : 'warning'">
							{{ scope.row.status === 'completed' ? '已完成' : scope.row.status === 'error' ? '错误' : '进行中' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="created" label="创建时间" align="center" sortable></el-table-column>
				<el-table-column label="操作" align="center">
					<template v-slot="scope">
						<el-button type="text" size="medium" @click="viewTaskDetails(scope.row)">任务详情</el-button>
						<el-button type="text" style="color: #f56c6c" size="medium" @click="confirmDelete(scope.row)">删除任务</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-empty v-else description="暂无最近任务，请先创建一个新任务。"></el-empty>
			<el-pagination
				v-if="tasks.length > 0"
				@current-change="handlePageChange"
				:current-page="currentPage"
				:page-size="pageSize"
				:page-sizes="[3, 6, 9]"
				@size-change="handleSizeChange"
				layout="sizes, prev, pager, next, jumper"
				:total="totalTasks"
				background
			></el-pagination>
		</el-card>
	</div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
	name: 'UseAppView',
	data() {
		return {
			guideVisible: true,
			activeStep: 0,
			form: {
				taskName: '',
				targetName: '',
				taskDescription: '',
				targetSequence: '',
				aiModel: '',
				screeningLibrary: ''
			},
			customLibraryForm: {
				libraryName: '',
				libraryDescription: ''
			},
			models: [], // 存储获取的AI模型列表
			libraries: [], // 存储获取的筛选库列表
			tasks: [], // 存储任务列表
			currentPage: 1,
			pageSize: 6, // 默认每页显示3个任务
			totalTasks: 0,
			fullscreenLoading: false, // 控制加载遮罩的显示
			customLibraryVisible: false,
			compoundFile: null,
			fileList: [] // 用于显示当前上传的文件
		};
	},
	computed: {
		paginatedTasks() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.tasks.slice(start, end);
		}
	},
	created() {
		// 在组件创建时获取模型和筛选库列表
		this.fetchModels();
		this.fetchLibraries();
		this.fetchTasks();
	},
	methods: {
		openCustomLibraryPanel() {
			this.customLibraryVisible = true;
		},
		handleBeforeUpload(file) {
			// 限制文件类型和大小
			if (file.type !== 'text/plain') {
				this.$message.error('仅支持 .txt 格式文件');
				return false;
			}
			if (file.size / 1024 / 1024 > 5) {
				this.$message.error('文件大小不能超过 5MB');
				return false;
			}

			// 如果已经有文件，则替换掉原来的文件
			if (this.fileList.length > 0) {
				this.fileList = [];
			}

			// 将新文件添加到列表
			this.fileList.push(file);
			this.compoundFile = file; // 更新 compoundFile 以供后续提交
			return false;
		},
		fillExample(exampleNumber) {
			if (exampleNumber === 1) {
				this.form.taskName = '新冠病毒Mpro抑制剂';
				this.form.targetName = 'Mpro';
				this.form.taskDescription =
					'Mpro是一种半胱氨酸蛋白酶，在病毒生命周期中的病毒蛋白加工阶段起到重要作用。Mpro通过切割病毒的多聚蛋白前体，产生功能性非结构蛋白（nsps），如复制酶和转录酶，这些酶对于病毒的RNA复制和基因组的处理至关重要。SARS-CoV-2中，Mpro负责介导多达11个切割位点的蛋白质水解反应。由于Mpro的切割位点与宿主细胞中的蛋白切割位点不相同，因此抑制Mpro有可能不会对宿主细胞的正常功能产生重大副作用，这使得它成为一个非常有吸引力的抗病毒药物靶点。';
				this.form.targetSequence =
					'SGFRKMAFPSGKVEGCMVQVTCGTTTLNGLWLDDVVYCPRHVICTSEDMLNPNYEDLLIRKSNHNFLVQAGNVQLRVIGHSMQNCVLKLKVDTANPKTPKYKFVRIQPGQTFSVLACYNGSPSGVYQCAMRPNFTIKGSFLNGSCGSVGFNIDYDCVSFCYMHHMELPTGVHAGTDLEGNFYGPFVDRQTAQAAGTDTTITVNVLAWLYAAVINGDRWFLNRFTTTLNDFNLVAMKYNYEPLTQDHVDILGPLSAQTGIAVLDMCASLKELLQNGMNGRTILGSALLEDEFTPFDVVRQCSGVTFQ';
				this.form.aiModel = this.models[0].model_id; // 假设使用第一个模型
				this.form.screeningLibrary = this.libraries[0].library_id; // 假设使用第一个筛选库
			} else if (exampleNumber === 2) {
				this.form.taskName = 'EGFR新药靶点筛选任务';
				this.form.targetName = 'EGFR';
				this.form.taskDescription =
					'EGFR是表皮生长因子受体（HER）家族成员之一，广泛分布于哺乳动物上皮细胞、成纤维细胞、胶质细胞、角质细胞等细胞表面，EGFR信号通路对细胞的生长、增殖和分化等生理过程发挥重要的作用。然而当EGFR发生突变时，导致EGFR信号通路的持续激活，从而导致细胞异常增殖。';
				this.form.targetSequence =
					'GSGEAPNQALLRILKETEFKKIKVLGSGAFGTVYKGLWIPEGEKVKIPVAIKELREATSPKANKEILDEAYVMASVDNPHVCRLLGICLTSTVQLITQLMPFGCLLDYVREHKDNIGSQYLLNWCVQIAKGMNYLEDRRLVHRDLAARNVLVKTPQHVKITDFGLAKLLGAEEKEYHAEGGKVPIKWMALESILHRIYTHQSDVWSYGVTVWELMTFGSKPYDGIPASEISSILEKGERLPQPPICTIDVYMIMVKCWMIDADSRPKFRELIIEFSKMARDPQRYLVIQGDERMHLPSPTDSNFYRALMDEEDMDDVVDADEYLIPQQG';
				this.form.aiModel = this.models[1].model_id; // 假设使用第二个模型
				this.form.screeningLibrary = this.libraries[1].library_id; // 假设使用第二个筛选库
			} else if (exampleNumber === 3) {
				this.form.taskName = 'PKMYT1药物筛选任务';
				this.form.targetName = 'PKMYT1';
				this.form.taskDescription =
					'PKMYT1在非恶性真核体细胞中负向调控细胞的有丝分裂，它在调控细胞周期及维持DNA的正常复制中发挥重要作用。PKMYT1可通过特异性的促进与调节细胞周期相关的细胞周期依赖性激酶蛋白复合物中的CDK1磷酸化，使CDK1-cyclinB复合物滞留在细胞质中，减少其入核，从而干扰细胞周期的分布。己有多项研宄显示，PKMYT1 在卵巢癌、乳腺癌、肾癌以及前列腺癌、膀胱癌等恶性肿瘤中高表达，在上述恶性肿瘤的进展中发挥促癌基因的作用。';
				this.form.targetSequence =
					'MHHHHHHSSGVDLGTENLYFQSMHQLQPRRVSFRGEASETLQSPGYDPSRPESFFQQSFQRLSRLGHGSYGEVFKVRSKEDGRLYAVKRSMSPFRGPKDRARKLAEVGSHEKVGQHPCCVRLEQAWEEGGILYLQTELCGPSLQQHCEAWGASLPEAQVWGYLRDTLLALAHLHSQGLVHLDVKPANIFLGPRGRCKLGDFGLLVELGTAGAGEVQEGDPRYMAPELLQGSYGTAADVFSLGLTILEVACNMELPHGGEGWQQLRQGYLPPEFTAGLSSELRSVLVMMLEPDPKLRATAEALLALPVLRQP';
				this.form.aiModel = this.models[2].model_id; // 假设使用第三个模型
				this.form.screeningLibrary = this.libraries[1].library_id; // 假设使用第三个筛选库
			}
			this.updateStep(); // 更新步骤状态
		},
		async handleCustomLibrarySubmit() {
			this.$refs.customLibraryFormRef.validate(async (valid) => {
				if (valid) {
					const formData = new FormData();
					formData.append('user_id', 1);
					formData.append('library_name', this.customLibraryForm.libraryName);
					formData.append('library_description', this.customLibraryForm.libraryDescription);
					formData.append('compound_file', this.compoundFile);

					try {
						const response = await axios.post('/api/libraries/upload', formData, {
							headers: {
								'Content-Type': 'multipart/form-data'
							}
						});
						this.$message.success('上传成功: ' + response.data.message);
						this.customLibraryVisible = false;
						this.customLibraryForm.libraryName = '';
						this.customLibraryForm.libraryDescription = '';
						this.compoundFile = null;
						this.fetchLibraries(); // 上传成功后刷新筛选库列表
					} catch (error) {
						if (error.response && error.response.data && error.response.data.error) {
							// 如果后端返回了具体的错误信息，显示这个错误信息
							this.$message.error(error.response.data.error);
						} else {
							// 如果没有具体错误信息，显示通用错误提示
							this.$message.error('上传自定义筛选库失败，请重试');
						}
					}
				} else {
					this.$message.warning('请填写所有必填项');
				}
			});
			this.customLibraryForm.libraryName = '';
			this.customLibraryForm.libraryDescription = '';
			this.compoundFile = null;

			this.fileList = [];
		},

		async fetchModels() {
			try {
				this.fullscreenLoading = true;
				const response = await axios.get('/api/models');
				this.models = response.data;
			} catch (error) {
				Message.error('获取模型列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async fetchLibraries() {
			const userId = 1;
			try {
				this.fullscreenLoading = true;
				const response = await axios.get('/api/libraries', {
					params: {
						user_id: userId
					}
				});
				this.libraries = response.data;
			} catch (error) {
				Message.error('获取筛选库列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async fetchTasks() {
			try {
				this.fullscreenLoading = true;
				// 假设这里是获取当前用户ID为1的任务
				const userId = 1;
				const response = await axios.get(`/api/tasks/${userId}`);
				this.tasks = response.data.map((task) => ({
					id: task.task_id,
					name: task.task_name,
					status: task.task_status,
					created: task.create_time,
					target_name: task.target_name,
					task_description: task.task_description
				}));
				this.totalTasks = this.tasks.length;
			} catch (error) {
				Message.error('获取任务列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async handleSubmit() {
			// 去除表单内容的空格和换行符
			this.trimForm();

			this.$refs.taskForm.validate(async (valid) => {
				// 验证表单是否填写完整
				if (valid) {
					try {
						const newTask = {
							task_name: this.form.taskName,
							task_description: this.form.taskDescription,
							target_name: this.form.targetName,
							target_sequence: this.form.targetSequence,
							model_id: this.form.aiModel,
							library_id: this.form.screeningLibrary,
							user_id: 1 // 假设用户ID为1
						};
						const response = await axios.post('/api/tasks', newTask);
						Message.success('提交任务成功');
						this.fetchTasks(); // 更新任务列表
						this.handleReset(); //重置表单
					} catch (error) {
						Message.error('提交任务失败');
					}
				} else {
					Message.warning('请填写完整的表单信息'); // 提示用户表单未填写完整
				}
			});
		},
		trimForm() {
			Object.keys(this.form).forEach((key) => {
				if (typeof this.form[key] === 'string') {
					this.form[key] = this.form[key].trim().replace(/[\\/]/g, '');
				}
			});
		},

		handleReset() {
			// 重置表单
			this.$refs['taskForm'].resetFields();
			this.activeStep = 0;
		},
		viewTaskDetails(row) {
			// 跳转到任务详情页面
			this.$router.push({ name: 'TaskDetails', params: { taskId: row.id } });
		},
		confirmDelete(row) {
			// 删除任务前确认
			MessageBox.confirm('确定要删除这个任务吗？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(async () => {
					try {
						await axios.delete(`/api/tasks/${row.id}`);
						Message.success('任务删除成功');
						this.fetchTasks(); // 更新任务列表
					} catch (error) {
						Message.error('删除任务失败');
					}
				})
				.catch(() => {});
		},
		handlePageChange(page) {
			// 处理分页逻辑
			this.currentPage = page;
		},
		handleSizeChange(size) {
			this.pageSize = size;
			this.currentPage = 1; // 当更改每页数量时，重置到第一页
		},
		updateStep() {
			const { taskName, targetName, taskDescription, targetSequence, aiModel, screeningLibrary } = this.form;

			if (taskName && targetName && taskDescription && targetSequence) {
				this.activeStep = 1;

				if (aiModel) {
					this.activeStep = 2;

					if (screeningLibrary) {
						this.activeStep = 3;
					}
				}
			}
		}
	}
};
</script>

<style scoped>
.use-app-container {
	padding: 20px;
	font-family: Arial, sans-serif;
}
.custom-library-form {
	padding: 20px;
}
.upload-section {
	margin-top: 10px;
}
.file-name {
	margin-top: 10px;
	color: #666;
}
.upload-hint {
	margin-top: 5px;
	font-size: 12px;
	color: #999;
}
.form-section {
	margin-bottom: 20px;
	background: #ffffff;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.task-form {
	max-width: 100%;
	margin: 0 auto;
}
.form-actions {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
	margin-top: 20px;
}
.example-fill {
	margin: 20px 0;
	text-align: left;
}
.example-buttons {
	display: flex;
	justify-content: flex-end;
	display: flex;
	gap: 10px;
}
.recent-tasks-section {
	background: #ffffff;
	padding: 20px;
	border-radius: 8px;
	margin-top: 20px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
h2 {
	margin-bottom: 20px;
	text-align: left;
	color: #333;
}
.el-pagination {
	margin-top: 20px;
	text-align: center;
}
.guide-content {
	font-size: 14px;
	text-align: left;
	line-height: 1.8;
}
.task-steps {
	margin-top: 30px;
	margin-bottom: 30px;
}
</style>
